package com.liliudong.template.biz.service.sys.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.liliudong.template.biz.mapper.sys.SysRoleMenuMapper;
import com.liliudong.template.biz.service.sys.SysRoleMenuService;
import com.liliudong.template.common.constant.ExMessage;
import com.liliudong.template.common.entity.sys.SysRoleMenu;
import com.liliudong.template.common.exception.BizException;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static com.liliudong.template.common.entity.sys.table.SysRoleMenuTableDef.SYS_ROLE_MENU;

/**
 * SysRoleMenuService
 *
 * @author liudo
 * @version 1.0
 * @project template-backend
 * @date 2024/7/31 14:32:25
 */
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements SysRoleMenuService {
    @Override
    public void saveBatchWithRoleId(Long roleId, List<Long> menuIds) {
        if (CollectionUtil.isEmpty(menuIds)) {
            return;
        }
        if (Objects.isNull(roleId)) {
            throw new BizException(ExMessage.ROLE_EMPTY);
        }
        List<SysRoleMenu> roleMenuList = menuIds.stream()
                .map(menuId -> {
                    SysRoleMenu roleMenu = new SysRoleMenu();
                    roleMenu.setRoleId(roleId);
                    roleMenu.setMenuId(menuId);
                    return roleMenu;
                }).collect(Collectors.toList());
        saveBatch(roleMenuList);
    }

    @Override
    public void removeByRoleId(Long roleId) {
        if (Objects.isNull(roleId)) {
            throw new BizException(ExMessage.ROLE_EMPTY);
        }
        remove(SYS_ROLE_MENU.ROLE_ID.eq(roleId));
    }

    @Override
    public Set<Long> listMenuIdsByRoleId(Long roleId, boolean isAdmin) {
        return queryChain()
                .select(SYS_ROLE_MENU.MENU_ID)
                .where(SYS_ROLE_MENU.ROLE_ID.eq(roleId).when(!isAdmin))
                .list()
                .stream()
                .map(SysRoleMenu::getMenuId)
                .collect(Collectors.toSet());
    }

    @Override
    public long countByMenuId(Long menuId) {
        return queryChain()
                .where(SYS_ROLE_MENU.MENU_ID.eq(menuId))
                .count();
    }
}
